import axios from 'axios';
import * as crypto from 'crypto';
export default class Youdao {
  constructor(option: any) {
    this.option = option;
  }
  option: any;
  async translate(query: any, option: any = {}) {
    const salt = new Date().getTime();
    const curtime = Math.round(new Date().getTime() / 1000);
    const str1 =
      this.option.appKey +
      Youdao.truncate(query) +
      salt +
      curtime +
      this.option.appSecret;
    const sign = crypto.createHash('sha256').update(str1).digest('hex');
    const res = await axios.get('https://openapi.youdao.com/api', {
      params: {
        q: query,
        appKey: this.option.appKey,
        salt,
        from: (option === null || option === 0 ? 0 : option.from) || 'auto',
        to: (option === null || option === 0 ? 0 : option.to) || 'auto',
        sign,
        signType: 'v3',
        curtime,
        vocabId: option === null || option === 0 ? 0 : option.vocabId,
      },
    });
    if (res.status === 200) {
      return res.data;
    }
    return Promise.reject(new YoudaoError('1', 'getInfo response Error', res));
  }
  static truncate(q: any) {
    const len = q.length;
    if (len <= 20) return q;
    return q.substring(0, 10) + len + q.substring(len - 10, len);
  }
}
export class YoudaoError extends Error {
  constructor(code: string, message: string, response: any) {
    super(message); // (1)
    this.code = code;
    this.response = response;
    this.name = 'YoudaoError'; // (2)
  }
  code: string;
  response: any;
  name: string;
}
